package com.caldremch.androidfoundation.http.func;

import android.util.Log;

import java.net.ConnectException;
import java.net.SocketTimeoutException;
import java.util.concurrent.TimeUnit;

import io.reactivex.Observable;
import io.reactivex.ObservableSource;
import io.reactivex.functions.Function;

/**
 * 重试机制
 */
public class ApiRetryFunc implements Function<Observable<? extends Throwable>, Observable<?>> {

    private final int mMaxRetries = 3;
    private final int mRetryDelayMillis = 5000;
    private int mRetryCount = 3;

    public ApiRetryFunc() {
    }

    @Override
    public Observable<?> apply(Observable<? extends Throwable> observable) throws Exception {
        return observable
                .flatMap(new Function<Throwable, ObservableSource<?>>() {
                    @Override
                    public ObservableSource<?> apply(Throwable throwable) throws Exception {
                        if (++mRetryCount <= mMaxRetries && (throwable instanceof SocketTimeoutException || throwable instanceof ConnectException)) {


                            Log.d("http", "response data error , it will try after" + mRetryDelayMillis + " millisecond, retry count " + mRetryCount);

                            return Observable.timer(mRetryDelayMillis, TimeUnit.MILLISECONDS);
                        }
                        //error未同意管理
                        return Observable.error(new Exception(throwable));
                    }
                });
    }
}
